package org.summer.lawyer.controller.wx;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.util.ObjectUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.summer.common.core.domain.R;
import org.summer.common.core.exception.ServiceException;
import org.summer.common.mybatis.core.page.PageQuery;
import org.summer.common.mybatis.core.page.TableDataInfo;
import org.summer.common.satoken.utils.LoginHelper;
import org.summer.lawyer.constant.SystemConstants;
import org.summer.lawyer.constant.enums.PaymentMethod;
import org.summer.lawyer.domain.bo.payorder.PayOrderBo;
import org.summer.lawyer.domain.bo.spuorder.CompletedOrderBo;
import org.summer.lawyer.domain.bo.spuorder.SpuOrderBo;
import org.summer.lawyer.domain.bo.spuorder.SpuOrderCreateBo;
import org.summer.lawyer.domain.bo.spuorderassign.SpuOrderAssignBo;
import org.summer.lawyer.domain.bo.spuorderassign.TakeCompletedOrderBo;
import org.summer.lawyer.domain.bo.spuorderassign.TakeOrderBo;
import org.summer.lawyer.domain.vo.payapp.PayAppVo;
import org.summer.lawyer.domain.vo.paychannel.PayChannelVo;
import org.summer.lawyer.domain.vo.payorder.PayOrderVo;
import org.summer.lawyer.domain.vo.payorder.TradeOrderVo;
import org.summer.lawyer.domain.vo.spuorder.SpuOrderVo;
import org.summer.lawyer.domain.vo.spuorderassign.SpuAssignOrderStat;
import org.summer.lawyer.domain.vo.spuorderassign.SpuOrderAssignVo;
import org.summer.lawyer.service.*;

/**
 *
 */
@Tag(name = "微信小程序订单接口", description = "微信小程序订单相关接口")
@Slf4j
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/wx/trade")
public class WxTradeOrderController {


    private final ISpuOrderService spuOrderService;

    private final IPayOrderService payOrderService;

    private final IPayAppService payAppService;

    private final IPayChannelService payChannelService;

    private final ISpuOrderAssignService spuOrderAssignService;


    @Parameters({
            @Parameter(name = "appId", description = "小程序AppId", required = true),
            @Parameter(name = "openId", description = "小程序用户openId", required = true),
            @Parameter(name = "wxUserId", description = "微信用户ID", required = true),
            @Parameter(name = "spuId", description = "商品ID(第一次下单必须传)", required = true),
            @Parameter(name = "count", description = "购买数量，默认数量为1", required = true),
            @Parameter(name = "contactPhone", description = "联系电话", required = true),
             @Parameter(name = "orderId", description = "订单ID", required = true)
    })
    @Operation(summary = "微信用户提交订单", description = "提交订单")
    @SaCheckLogin
    @PostMapping("/submitOrder")
    public R<TradeOrderVo> submitOrder(@Validated @RequestBody SpuOrderCreateBo bo) {
        //支付应用是否关闭
        PayAppVo payAppVo = payAppService.selectPayAppVoByDefault();
        if (payAppVo == null || SystemConstants.INACTIVE.equals(payAppVo.getStatus())) {
            throw new ServiceException("订单应用维护中，暂停服务");
        }
        PayChannelVo channelVo = payChannelService.selectPayChannelVoByCode(PaymentMethod.WECHAT_MINIAPP.getCode(), bo.getAppId());
        if (bo.getOrderId() != null && bo.getOrderId() > 0L) {
            log.info("[submitOrder][订单ID:{}]重新下单", bo.getOrderId());
            SpuOrderVo spuOrderVo = spuOrderService.selectSpuOrderVoById(bo.getOrderId());
            bo.setSpuId(spuOrderVo.getSpuId());
            bo.setContactPhone(spuOrderVo.getContactPhone());
            bo.setContactName(spuOrderVo.getUserName());
        }
        bo.setCount(1);
        SpuOrderVo spuOrder = spuOrderService.create(bo);
        TradeOrderVo tradeOrder = new TradeOrderVo();
        tradeOrder.setOrderId(spuOrder.getOrderId());

        if (ObjectUtil.isNotNull(channelVo) && SystemConstants.ACTIVE.equals(channelVo.getStatus())) {
            //创建支付订单
            PayOrderBo payOrderBo = new PayOrderBo();
            payOrderBo.setWxAppId(bo.getAppId());
            payOrderBo.setUserId(bo.getWxUserId());
            payOrderBo.setOrderId(spuOrder.getOrderId());
            payOrderBo.setOpenId(bo.getOpenId());
            payOrderBo.setChannelCode(PaymentMethod.WECHAT_MINIAPP.getCode());
            PayOrderVo payOrderResult = payOrderService.sumbitPayOrderVo(payOrderBo);
            tradeOrder.setPayNo(payOrderBo.getPayNo());
            tradeOrder.setTimeStamp(payOrderResult.getTimeStamp());
            tradeOrder.setNonceStr(payOrderResult.getNonceStr());
            tradeOrder.setSignType(payOrderResult.getSignType());
            tradeOrder.setPackageValue(payOrderResult.getPackageValue());
            tradeOrder.setPaySign(payOrderResult.getPaySign());
        }
        return R.ok(tradeOrder);
    }

    @Parameters({
            @Parameter(name = "pageSize", description = "分页大小", required = true),
            @Parameter(name = "pageNum", description = "当前页数", required = true),
            @Parameter(name = "orderStatus", description = "订单状态(Paid=已付款，Completed=已完成)", required = false),
            @Parameter(name = "review", description = "评价状态(0待评价，1已评价）", required = false)
    })
    @Operation(summary = "用户订单列表", description = "查询用户相关订单列表")
    @SaCheckLogin
    @GetMapping("/listOrder")
    public TableDataInfo<SpuOrderVo> list(SpuOrderBo bo, PageQuery pageQuery) {
        Long userId = LoginHelper.getUserId() != null ? LoginHelper.getUserId() : 0L;
        if(bo.getUserId() == null){
            bo.setUserId(userId);
        }
        bo.setPayed("1");
        return spuOrderService.selectUserOrderPageList(bo, pageQuery);
    }

    @Parameters({
            @Parameter(name = "orderId", description = "订单ID", required = true)
    })
    @Operation(summary = "通过订单ID查询订单详情", description = "获取订单详情")
    @SaCheckLogin
    @GetMapping("/{orderId}")
    public R<SpuOrderVo> getSpuOrder(@NotNull(message = "主键不能为空") @PathVariable("orderId") Long orderId) {
        return R.ok(spuOrderService.selectSpuOrderVoById(orderId));
    }


    @Parameters({
            @Parameter(name = "lawFirmId", description = "律所ID", required = true),
            @Parameter(name = "pageSize", description = "分页大小", required = true),
            @Parameter(name = "pageNum", description = "当前页数", required = true),
            @Parameter(name = "review", description = "评价状态(0待评价，已评价）", required = false),
            @Parameter(name = "orderBeginTime", description = "订单开始时间", required = false),
            @Parameter(name = "orderEndTime", description = "订单截止时间", required = false),
            @Parameter(name = "overtime", description = "是否超时（0没有超时，1已经超时）", required = false),
            @Parameter(name = "dispatchStatus", description = "Processing=处理中(已分派，还没接单），Confirmed=已接单，Completed=处理完成，Returned=已退回", required = false)

    })
    @Operation(summary = "律师端分页查询我的订单接口", description = "分页查询我的订单接口")
    @SaCheckLogin
    @GetMapping("/listAssignOrder")
    public TableDataInfo<SpuOrderAssignVo> listAssignOrder(SpuOrderAssignBo bo, PageQuery pageQuery) {
        if (bo.getLawFirmId() == null) {
            bo.setLawFirmId(0L);
        }
        return spuOrderAssignService.selectPageLawFirmList(bo, pageQuery);
    }


    @Parameters({
            @Parameter(name = "trackingNumber", description = "派单编号", required = true),
    })
    @Operation(summary = "查询派单详情接口", description = "查询派单详情接口")
    @SaCheckLogin
    @GetMapping("/assignOrder/{trackingNumber}")
    public R<SpuOrderAssignVo> getAssignOrder(@NotEmpty(message = "订单编号不能为空") @PathVariable("trackingNumber") String trackingNumber) {
        return R.ok(spuOrderAssignService.selectSpuOrderAssignVoByTrackingNumber(trackingNumber));
    }


    @Parameters({
            @Parameter(name = "trackingNumber", description = "派单编号", required = true),
            @Parameter(name = "wxUserId", description = "微信用户ID", required = true),
            @Parameter(name = "lawFirmId", description = "律所ID", required = true)
    })
    @Operation(summary = "律师确认接单接口", description = "律师或律所接单确认")
    @SaCheckLogin
    @PostMapping("/takeOrder")
    public R<Void> takeOrder(@Validated @RequestBody TakeOrderBo bo) {
        spuOrderAssignService.takeOrder(bo);
        return R.ok("操作成功");
    }

    @Parameters({
            @Parameter(name = "trackingNumber", description = "派单编号")
    })
    @Operation(summary = "申请完成订单接口", description = "律师端申请完成订单")
    @SaCheckLogin
    @PostMapping("/takeCompletedOrder")
    public R<Void> takeCompletedOrder(@Validated @RequestBody TakeCompletedOrderBo bo) {
       spuOrderService.processedOrder(bo);
        return R.ok("操作成功");
    }

    @Parameters({
            @Parameter(name = "wxUserId", description = "微信用户ID", required = true),
            @Parameter(name = "orderId", description = "订单ID", required = true)
    })
    @Operation(summary = "用户端完成订单", description = "用户完成订单")
    @SaCheckLogin
    @PostMapping("/completedOrder")
    public R<Void> completedOrder(@Validated @RequestBody CompletedOrderBo bo) {
        spuOrderService.completedOrder(bo);
        return R.ok();
    }

    @Parameters({
            @Parameter(name = "wxUserId", description = "微信用户ID", required = true)
    })
    @Operation(summary = "订单统计", description = "订单统计")
    @SaCheckLogin
    @GetMapping("/orderStat/{wxUserId}")
    public R<SpuAssignOrderStat> orderStat(@NotNull(message = "主键ID不能为空") @PathVariable("wxUserId") Long wxUserId) {
        return R.ok(spuOrderService.selectSpuAssignOrderStatByWxUserId(wxUserId));
    }

    @SaIgnore
    @PostMapping("/testOrder")
    public R<TradeOrderVo> testOrder(@Validated @RequestBody SpuOrderCreateBo bo) {
        //支付应用是否关闭
        PayAppVo payAppVo = payAppService.selectPayAppVoByDefault();
        if (payAppVo == null || SystemConstants.INACTIVE.equals(payAppVo.getStatus())) {
            throw new ServiceException("订单应用维护中，暂停服务");
        }
        PayChannelVo channelVo = payChannelService.selectPayChannelVoByCode(PaymentMethod.WECHAT_MINIAPP.getCode(), bo.getAppId());
        if (bo.getOrderId() != null && bo.getOrderId() > 0L) {
            log.info("[submitOrder][订单ID:{}]重新下单", bo.getOrderId());
            SpuOrderVo spuOrderVo = spuOrderService.selectSpuOrderVoById(bo.getOrderId());
            bo.setSpuId(spuOrderVo.getSpuId());
            bo.setContactPhone(spuOrderVo.getContactPhone());
            bo.setContactName(spuOrderVo.getUserName());
        }
        bo.setCount(1);
        SpuOrderVo spuOrder = spuOrderService.create(bo);
        TradeOrderVo tradeOrder = new TradeOrderVo();
        tradeOrder.setOrderId(spuOrder.getOrderId());

        if (ObjectUtil.isNotNull(channelVo) && SystemConstants.ACTIVE.equals(channelVo.getStatus())) {
            //创建支付订单
            PayOrderBo payOrderBo = new PayOrderBo();
            payOrderBo.setWxAppId(bo.getAppId());
            payOrderBo.setUserId(bo.getWxUserId());
            payOrderBo.setOrderId(spuOrder.getOrderId());
            payOrderBo.setOpenId(bo.getOpenId());
            payOrderBo.setChannelCode(PaymentMethod.WECHAT_MINIAPP.getCode());
            PayOrderVo payOrderResult = payOrderService.createTestPayOrder(payOrderBo);

        }
        return R.ok(tradeOrder);
    }
}
